package com.ztomorrow.ying_cun_plus.auth;

import com.ztomorrow.ying_cun_plus.constant.front.ErrorCodeEnum;
import com.ztomorrow.ying_cun_plus.dto.AuthorInfoDto;
import com.ztomorrow.ying_cun_plus.exception.BusinessException;
import com.ztomorrow.ying_cun_plus.service.impl.AuthorServiceImpl;
import com.ztomorrow.ying_cun_plus.service.impl.UserServiceImpl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@RequiredArgsConstructor
public class AuthorAuthStrategy implements AuthStrategy {

    private final UserServiceImpl userService;
    private final AuthorServiceImpl authorService;

    private static final List<String> EXCLUDE_URI = List.of(
             "/author/register",
             "/author/status"
    );

    @Override
    public void auth(String token, String requestUri) throws BusinessException {
        // 统一账号认证
        Long userId = authSSO( userService, token);
        if (EXCLUDE_URI.contains(requestUri)) {
            // 该请求不需要进行作家权限认证
            return;
        }
        // 作家权限认证
        AuthorInfoDto authorInfo = authorService.getAuthor(userId);
        if (Objects.isNull(authorInfo)) {
            // 作家账号不存在，无权访问作家专区
            throw new BusinessException(ErrorCodeEnum.USER_UN_AUTH);
        }

        // 设置作家ID到当前线程
        UserHolder.setAuthorId(authorInfo.getId());
    }
}
